home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1995 February: Tool Chest / Dev.CD Feb 95 / Dev.CD Feb 95.toast / Sample Code / Snippets / Toolbox / AddResMenu7.1 / AddResMenu7.1.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-11-12  |  35.6 KB  |  915 lines  |  [TEXT/MPS ]

  1. /* MyAddResMenu */
  2. /* There is a minor bug in system 7.1 (oh no!) */
  3. /* AddResMenu will only alphabatize 'FONT' resources, all others */
  4. /* will just be displayed in the order they appear in the resource map */
  5. /* of the resource fork. */
  6. /* This isn't harmful, it's just a little ugly. */
  7. /* Fixing it is pretty simple, just use the function in this sample */
  8. /* called MyAddResMenu */
  9. /* C.K. Haun */
  10. /* Apple DTS */
  11. /* Of course, Copyright 1991-1992, Apple Computer Inc. */
  12.  
  13. #include "AddResMenu7.1.h"
  14.  
  15. /* prototypes */
  16.  
  17. void InitalizeApp(void);
  18. void DoDiskEvents(long dinfo);                              /* hi word is error code, lo word is drive number */
  19. void DrawMain(WindowPtr drawIt);
  20. Boolean DoSelected(long val);
  21. void SizeMain(WindowPtr theWindow);
  22. void InitAEStuff(void);
  23. void DoHighLevel(EventRecord *AERecord);
  24. void DoDaCall(MenuHandle themenu, long theit);
  25. void DoDocumentClick(WindowPtr theWindow);
  26.  
  27. pascal OSErr AEOpenHandler(AppleEvent *messagein, AppleEvent *reply, long refIn);
  28. pascal OSErr AEOpenDocHandler(AppleEvent *messagein, AppleEvent *reply, long refIn);
  29. pascal OSErr AEPrintHandler(AppleEvent *messagein, AppleEvent *reply, long refIn);
  30. pascal OSErr AEQuitHandler(AppleEvent *messagein, AppleEvent *reply, long refIn);
  31.  
  32. void SampleHelpDialog(void);
  33.  
  34. WindowPtr AddNewWindow(short theID);
  35. short HasSelectionRange(DialogPeek inputDialog);
  36. Boolean IsEditKey(char theKey, short modifiers);
  37. void AddAResourceType(void);
  38. void MyAddResMenu(ResType theType, MenuHandle theMenu, short afterItem);
  39. pascal Boolean filterIt(DialogPtr inputDialog, EventRecord *myDialogEvent, short *theDialogItem);
  40. ControlHandle SnatchHandle(DialogPtr thebox, short theGetItem);
  41. void CleanUpMetaChars(Str255 theString);
  42. void NilProc(void);
  43. /* one external */
  44. extern void _DataInit();                                    /* this is the C initialization code */
  45.  
  46. /* globals */
  47. Boolean gQuit, gInBackground;
  48. unsigned long gMySleep;
  49. ProcessSerialNumber gOurSN;
  50. short gHelpItem;
  51.  
  52.  
  53. #pragma segment Main
  54. main()
  55. {
  56.     EventRecord myEventRecord;
  57.     WindowPtr twindow;
  58.     short fHit;
  59.     windowCHandle tempWCH;
  60.     
  61.     UnloadSeg((Ptr)_DataInit);                              /* throw out setup code */
  62.     InitalizeApp();
  63.     UnloadSeg((Ptr)InitalizeApp);                           /* get rid of my initialization code */
  64.     do {
  65.         
  66.         WaitNextEvent(everyEvent, &myEventRecord, gMySleep, nil);
  67.         switch (myEventRecord.what) {
  68.             case nullEvent:
  69.                 /* no nul processing in this sample */
  70.                 break;
  71.             case updateEvt:
  72.                 /* always check to see if it's my window */
  73.                 /* this may not seem necessary under 7.0, where it's unlikely or impossible for */
  74.                 /* a DA to be in your layer, but there are others*/
  75.                 /* who can stick themselves into your window list, */
  76.                 /* BalloonWriter comes quickly to mind */
  77.                 
  78.                 if (((WindowPeek)myEventRecord.message)->windowKind == kMyDocumentWindow) {
  79.                     tempWCH = (windowCHandle)GetWRefCon((WindowPtr)myEventRecord.message);
  80.                     (ProcPtr)((*tempWCH)->drawMe)((WindowPtr)myEventRecord.message);
  81.                 }
  82.                 break;
  83.             case mouseDown:
  84.                 /* first see where the hit was */
  85.                 fHit = FindWindow(myEventRecord.where, &twindow);
  86.                 
  87.                 switch (fHit) {
  88.                     Rect limitRect;
  89.                     Str255 tempString;
  90.                     long back;
  91.                     case inDesk:                            /* if they hit in desk, then the process manager */
  92.                         break;                              /* will switch us out, we don't need to do anything */
  93.                     case inMenuBar:
  94.                         DoSelected(MenuSelect(myEventRecord.where));
  95.                         break;
  96.                         
  97.                     case inSysWindow:
  98.                         
  99.                         /* pass to the system */
  100.                         SystemClick(&myEventRecord, twindow);
  101.                         break;
  102.                     case inContent:
  103.                         
  104.                         /* Handle content and control clicks here */
  105.                         
  106.                         if (FrontWindow()) {                /* don't do this unless we have a window open, silly */
  107.                             windowCHandle clicker;
  108.                             if (((WindowPeek)twindow)->windowKind == kMyDocumentWindow) {
  109.                                 
  110.                                 clicker = (windowCHandle)GetWRefCon(twindow);
  111.                                 /* jump to the content function stored for this window */
  112.                                 HLock((Handle)clicker);     /* lock it down so things don't get stupid */
  113.                                 (ProcPtr)((*clicker)->clickMe)(twindow);
  114.                                 HUnlock((Handle)clicker);       /* all done */
  115.                             }
  116.                         }
  117.                         break;
  118.                     case inDrag:
  119.                         DragWindow(twindow, myEventRecord.where, &qd.screenBits.bounds);
  120.                         break;
  121.                     case inGrow:
  122.                         /* Call GrowWindow here if you have a grow box */
  123.                         SetPort(twindow);
  124.                         limitRect = qd.screenBits.bounds;
  125.                         limitRect.top = kMinHeight;
  126.                         GetWTitle(twindow, tempString);
  127.                         /* I'm not letting the user shrink the window so */
  128.                         /* small that the title is truncated */
  129.                         limitRect.left = StringWidth(tempString) + 120;
  130.                         back = GrowWindow(twindow, myEventRecord.where, &limitRect);
  131.                         
  132.                         if (back) {
  133.                             windowCHandle tempWCH = (windowCHandle)GetWRefCon(twindow);
  134.                             Rect sizeRect = ((WindowPtr)twindow)->portRect;
  135.                             InvalRect(&sizeRect);
  136.                             sizeRect.top = sizeRect.bottom - 16;
  137.                             sizeRect.left = sizeRect.right - 16;
  138.                             EraseRect(&sizeRect);
  139.                             InvalRect(&sizeRect);
  140.                             SizeWindow(twindow, back & 0xffff, back >> 16, true);
  141.                             (ProcPtr)((*tempWCH)->sizeMe)(twindow);
  142.                         }
  143.                         InvalRect(&twindow->portRect);
  144.                         
  145.                         break;
  146.                     case inGoAway:
  147.                         /* Click in Close box */
  148.                         if (TrackGoAway(twindow, myEventRecord.where)) {
  149.                             if (((WindowPeek)twindow)->windowKind == kMyDocumentWindow)
  150.                                 (ProcPtr)((*(windowCHandle)((WindowPeek)twindow)->refCon)->closeMe)(twindow);
  151.                         }
  152.                         break;
  153.                     case inZoomIn:
  154.                     case inZoomOut:
  155.                         if (TrackBox(twindow, myEventRecord.where, fHit)) {
  156.                             windowCHandle tempWCH = (windowCHandle)GetWRefCon(twindow);
  157.                             SetPort(twindow);
  158.                             
  159.                             ZoomWindow(twindow, fHit, true);
  160.                             InvalRect(&twindow->portRect);
  161.                             if (((WindowPeek)twindow)->windowKind == kMyDocumentWindow)
  162.                                 (ProcPtr)((*tempWCH)->sizeMe)(twindow);
  163.                         }
  164.                 }
  165.             case mouseUp:
  166.                 /* don't care */
  167.                 break;
  168.                 /* same action for key or auto key */
  169.             case keyDown:
  170.             case autoKey:
  171.                 if (myEventRecord.modifiers & cmdKey)
  172.                     DoSelected(MenuKey(myEventRecord.message & charCodeMask));
  173.                 break;
  174.             case keyUp:
  175.                 /* don't care */
  176.                 break;
  177.             case diskEvt:
  178.                 
  179.                 /* I don't do anything special for disk events, this just passes them */
  180.                 /* to a function that checks for an error on the mount */
  181.                 DoDiskEvents(myEventRecord.message);
  182.                 break;
  183.             case activateEvt:
  184.                 
  185.                 if (myEventRecord.modifiers & activeFlag) {
  186.                     if (((WindowPeek)myEventRecord.message)->windowKind == kMyDocumentWindow) {
  187.                         
  188.                         tempWCH = (windowCHandle)GetWRefCon((WindowPtr)myEventRecord.message);
  189.                         (ProcPtr)((*tempWCH)->drawMe)((WindowPtr)myEventRecord.message);
  190.                     }
  191.                 }
  192.                 break;
  193.             case networkEvt:
  194.                 /* don't care */
  195.                 break;
  196.             case driverEvt:
  197.                 /* don't care */
  198.                 break;
  199.             case app4Evt:
  200.                 switch ((myEventRecord.message >> 24) & 0x0FF) {        /* high byte of message */
  201.                     case suspendResumeMessage:              /* suspend/resume is also an activate/deactivate */
  202.                         gInBackground = (myEventRecord.message & kResumeMask) == 0;
  203.                         break;
  204.                 }
  205.                 break;
  206.             default:
  207.                 break;
  208.                 /* This dispatches high level events (AppleEvents, for example) */
  209.                 /* to our dispatch routine.This is NEW in the event loop for */
  210.                 /* System 7 */
  211.             case kHighLevelEvent:
  212.                 DoHighLevel(&myEventRecord);
  213.                 break;
  214.                 
  215.         }
  216.     }
  217.             while (gQuit != true);
  218.     
  219. }
  220.  
  221. /* DoDaCall opens the requested DA.It's here as a seperate routine if you'd */
  222. /* like to perform some action or just know when a DA is opened in your */
  223. /* layer.Can be handy to track memory problems when a DA is opened */
  224. /* with an Option-open */
  225. void DoDaCall(MenuHandle themenu, long theit)
  226. {
  227.     long qq;
  228.     char DAname[255];
  229.     GetItem(themenu, theit, &DAname);
  230.     qq = OpenDeskAcc(DAname);
  231. }
  232.  
  233. /* end DoDaCall */
  234.  
  235. /* DoDiskEvents just checks the error code from the disk mount, */
  236. /* and puts up the 'Format' dialog (through DIBadMount) if need be */
  237. /* You can do much more here if you care about what disks are */
  238. /* in the drive */
  239. void DoDiskEvents(long dinfo)                               /* hi word is error code, lo word is drive number */
  240. {
  241.     short hival, loval, tommy;
  242.     Point fredpoint =  {
  243.         40, 40
  244.     };
  245.     hival = HiWord(dinfo);
  246.     loval = LoWord(dinfo);
  247.     if (hival != noErr)                                     /* something happened */ {
  248.         tommy = DIBadMount(fredpoint, dinfo);
  249.     }
  250. }
  251.  
  252. /* draws my window.Pretty simple */
  253. void DrawMain(WindowPtr drawIt)
  254. {
  255.     RgnHandle tempRgn;
  256.     Rect scratchRect;
  257.     BeginUpdate(drawIt);
  258.     SetPort(drawIt);
  259.     scratchRect = drawIt->portRect;
  260.     scratchRect.top = scratchRect.bottom - 15;
  261.     scratchRect.left = scratchRect.right - 15;
  262.     tempRgn = NewRgn();
  263.     GetClip(tempRgn);
  264.     ClipRect(&scratchRect);
  265.     DrawGrowIcon(drawIt);
  266.     SetClip(tempRgn);
  267.     DisposeRgn(tempRgn);
  268.     
  269.     EndUpdate(drawIt);
  270. }
  271.  
  272. /* my menu action taker.It returns a Boolean which I usually ignore, but it */
  273. /* mught be handy someday */
  274. /* I usually use it in an application to determine if a keystroke was accepted */
  275. /* by a menu or whether it should be passed along to any other key acceptors */
  276. Boolean DoSelected(long val)
  277. {
  278.     short loval, hival;
  279.     Boolean returnVal = false;
  280.     loval = LoWord(val);
  281.     hival = HiWord(val);
  282.     
  283.     switch (hival) {                                        /* switch off the menu number selected */
  284.         case kAppleMenu:                                    /* Apple menu */
  285.             if (loval != 1) {                               /* if this was not About, it's a DA */
  286.                 DoDaCall(GetMHandle(kAppleMenu), loval);
  287.             } else {
  288.                 Alert(kAboutBox, nil);                      /* do about box */
  289.             }
  290.             returnVal = true;
  291.             break;
  292.             
  293.         case kFileMenu:                                     /* File menu */
  294.             switch (loval) {
  295.                 
  296.                 case kQuitItem:
  297.                     gQuit = true;                           /* onlyitem */
  298.                     returnVal = true;
  299.                     break;
  300.                 default:
  301.                     break;
  302.             }
  303.             break;
  304.             
  305.         case kEditMenu:
  306.             /* edit menu junk */
  307.             /* don't care */
  308.             
  309.             switch (loval) {
  310.             default:
  311.                 break;
  312.             }
  313.             break;
  314.             
  315.         case kToolsMenu:
  316.             /* add all your test stuff here */
  317.             
  318.             switch (loval) {
  319.                 case kTestMenuChooseType:
  320.                     AddAResourceType();
  321.                     break;
  322.                 default:
  323.                     break;
  324.             }
  325.             break;
  326.             
  327.         case kHMHelpMenuID:                                 /* Defined in Balloons.h */
  328.             /* I only care about this item.If anything else is returned here, I don't know what */
  329.             /* it is, so I leave it alone.Remember, the Help Manager chapter says that */
  330.             /* Apple reserves the right to add and change things in the Help menu */
  331.             if (loval == gHelpItem)
  332.                 SampleHelpDialog();
  333.             break;
  334.             
  335.     }
  336.     HiliteMenu(0);
  337.     return(returnVal);
  338. }
  339.  
  340. void DoDocumentClick(WindowPtr theWindow)
  341. {
  342.     
  343. }
  344.  
  345. /* InitAEStuff installs my appleevent handlers */
  346. void InitAEStuff(void)
  347. {
  348.     AEinstalls HandlersToInstall[] =  {
  349.         {
  350.             kCoreEventClass, kAEOpenApplication, AEOpenHandler
  351.         },  {
  352.             kCoreEventClass, kAEOpenDocuments, AEOpenDocHandler
  353.         },  {
  354.             kCoreEventClass, kAEQuitApplication, AEQuitHandler
  355.         },  {
  356.             kCoreEventClass, kAEPrintDocuments, AEPrintHandler
  357.         }, 
  358.         /* The above are the four required AppleEvents. */
  359.         
  360.     };
  361.     
  362.     OSErr aevtErr = noErr;
  363.     long aLong = 0;
  364.     Boolean gHasAppleEvents = false;
  365.     /* Check this machine for AppleEvents.If they are not here (ie not 7.0)
  366.     * then we exit */
  367.     gHasAppleEvents = (Gestalt(gestaltAppleEventsAttr, &aLong) == noErr);
  368.     /* The following series of calls installs all our AppleEvent Handlers.
  369.     * These handlers are added to the application event handler list that 
  370.     * the AppleEvent manager maintains.So, whenever an AppleEvent happens
  371.     * and we call AEProcessEvent, the AppleEvent manager will check our
  372.     * list of handlers and dispatch to it if there is one.
  373.     */
  374.     if (gHasAppleEvents) {
  375.         register qq;
  376.         for (qq = 0; qq < ((sizeof(HandlersToInstall) / sizeof(AEinstalls))); qq++) {
  377.             aevtErr = AEInstallEventHandler(HandlersToInstall[qq].theClass, HandlersToInstall[qq].theEvent,
  378.                                             HandlersToInstall[qq].theProc, 0, false);
  379.             if (aevtErr) {
  380.                 ExitToShell();                              /* just fail, baby */
  381.             }
  382.         }
  383.     } else {
  384.         ExitToShell();
  385.     }
  386. }
  387.  
  388. /* end InitAEStuff */
  389.  
  390. /* I'm not doing error handling in this sample for clarities sake, you should. Hah, */
  391. /* easy for me to say, huh? */
  392. void DoHighLevel(EventRecord *AERecord)
  393. {
  394.     OSErr myErr;
  395.     myErr = AEProcessAppleEvent(AERecord);
  396.     
  397. }
  398.  
  399. /* end DoHighLevel */
  400.  
  401. /* This is the standard Open Application event.*/
  402. pascal OSErr AEOpenHandler(AppleEvent *messagein, AppleEvent *reply, long refIn)
  403. {
  404.     WindowPtr myWindow;
  405.  
  406. #pragma unused (messagein,reply,refIn)
  407.     /* we of course don't do anything here in this simple app */
  408.     /* except open our window */
  409.     myWindow = AddNewWindow(kDocWindowResID);
  410.     
  411.     return(noErr);
  412. }
  413.  
  414. /* end AEOpenHandler */
  415.  
  416. /* Open Doc, opens our documents.Remember, this can happen at application start AND */
  417. /* anytime else.If your app is up and running and the user goes to the desktop, hilites one */
  418. /* of your files, and double-clicks or selects Open from the finder File menu this event */
  419. /* handler will get called. Which means you don't do any initialization of globals here, or */
  420. /* anything else except open then doc.*/
  421. /* SO-- Do NOT assume that you are at app start time in this */
  422. /* routine, or bad things will surely happen to you. */
  423.  
  424. pascal OSErr AEOpenDocHandler(AppleEvent *messagein, AppleEvent *reply, long refIn)
  425. {
  426. #pragma unused (messagein,refIn,reply)
  427.     /* we of course don't do anything here */
  428.     return(errAEEventNotHandled);                           /* we have no docs, so no odoc events should come to us */
  429. }
  430.  
  431. pascal OSErr AEPrintHandler(AppleEvent *messagein, AppleEvent *reply, long refIn)
  432. {                                                           /* no printing handler in yet, so we'll ignore this */
  433.     /* the operation is functionally identical to the ODOC event, with the additon */
  434.     /* of calling your print routine.*/
  435. #pragma unused (messagein,refIn,reply)
  436.     /* we of course don't do anything here */
  437.     return(errAEEventNotHandled);                           /* we have no docs, so no pdoc events should come to us */
  438. }
  439.  
  440. /* Standard Quit event handler, to handle a Quit event from the Finder, for example.*/
  441. /* ••••• DO NOT CALL EXITTOSHELL HERE ••••• or you will never have a happy life.*/
  442. /* OK, it's a few months after I wrote that comment, and I've seen a lot of code */
  443. /* come through DTS that calls ExitToShell from quit handlers.Let me explain... */
  444. /* When an AppleEvent Handler is called (like this quit handler) you are ALMOST */
  445. /* 100% in your application world.A5 is right, you can call any toolbox function, */
  446. /* you can call your own routines, everything _seems_ like you are in complete*/
  447. /* control.Well, almost but not quite.The routine has been dispatch to from the */
  448. /* AppleEvent Manager's space, so you _must_ return to that at some point! */
  449. /* Which is why you can't call ETS from here.When you call ExitToShell from an */
  450. /* AE Handler, the most likely thing that happens is the FInder quits, and your*/
  451. /* application keeps running.Which ain't what you want, y'know? */
  452. /* so, DON'T CALL EXITTOSHELL FROM AN APPLEEVENT HANDLER!!!!!!!!!!!!!! */
  453. pascal OSErr AEQuitHandler(AppleEvent *messagein, AppleEvent *reply, long refIn)
  454. {
  455. #pragma unused (messagein,refIn,reply)
  456.     gQuit = true;
  457.     return(noErr);
  458. }
  459.  
  460. /* This is my sample help dialog.Does not do anything, expand as you need */
  461. void SampleHelpDialog(void)
  462. {
  463.     DialogPtr tdial = GetNewDialog(kSampHelp, nil, (WindowPtr)-1);
  464.     short itemhit = 0;
  465.     while (itemhit != 1) {
  466.         ModalDialog((ModalFilterProcPtr)nil, &itemhit);
  467.     }
  468.     DisposDialog(tdial);
  469. }
  470.  
  471. WindowPtr AddNewWindow(short theID)
  472. {
  473.     windowCHandle setControls;
  474.     WindowPtr tempWP;
  475.     short cnt = 0;
  476.     Str31 wtitle;
  477.     tempWP = GetNewWindow(theID, 0, (WindowPtr)-1);         /* get a new window */
  478.     ((WindowPeek)tempWP)->windowKind = kMyDocumentWindow;       /* mark it as my document window */
  479.     setControls = (windowCHandle)NewHandleClear(sizeof(windowControl));     /* add our control structure to it */
  480.     SetWRefCon(tempWP, (long)setControls);                  /* stop stuffing refCon directly <ckh 1.0.3> */
  481.     HLock((Handle)setControls);                             /* lock it down while we fill it*/
  482.     
  483.     /* add pointers to our procedures for drawing, saving, and closing */
  484.     /* This way, all I need is one dispatch point for drawing, closing */
  485.     /* or whatever, I don't have to case off the window kind to go to the*/
  486.     /* correct routine.Kinda like object-oriented programming, but I won't */
  487.     /* admit that. */
  488.     (*setControls)->drawMe = (ProcPtr)DrawMain;
  489.     (*setControls)->clickMe = (ProcPtr)DoDocumentClick;
  490.     (*setControls)->sizeMe = (ProcPtr)SizeMain;
  491.     (*setControls)->generalData = NewHandle(0);
  492.     return(tempWP);
  493. }
  494.  
  495. void SizeMain(WindowPtr theWindow)
  496. {
  497.     WindowPtr tempWP;
  498.     GetPort(&tempWP);
  499.     InvalRect(&theWindow->portRect);
  500.     SetPort(tempWP);
  501. }
  502.  
  503. void NilProc(void)
  504. {
  505.     
  506. }
  507.  
  508. /* AddAResourceType asks for the resource type to add to the menu */
  509. /* it preflights to see if at least one exists, then passes of to MyAddResMenu */
  510. void AddAResourceType(void)
  511. {
  512.     Rect tempRect;
  513.     short tempItem;
  514.     Handle tempHandle;
  515.     Str15 myStr;
  516.     ResType theType;
  517.     short hitItem;
  518.     DialogPtr myDialog = GetNewDialog(kResTypeDialog, nil, (WindowPtr)-1);
  519.     
  520.     /* New System 7 dialog manager calls, see tech note #304 */
  521.     /* interface to these calls is in AddResMenu7.1.h */
  522.     SetDialogDefaultItem(myDialog, ok);
  523.     SetDialogCancelItem(myDialog, cancel);
  524.     SetDialogTracksCursor(myDialog, true);
  525.     
  526.     do {
  527.         ModalDialog((ModalFilterProcPtr)filterIt, &hitItem);
  528.     }
  529.             while (hitItem != ok && hitItem != cancel);
  530.     
  531.     if (hitItem == ok) {
  532.         
  533.         /* get the type and hammer it */
  534.         GetDItem(myDialog, kResTypeEditLine, &tempItem, &tempHandle, &tempRect);
  535.         GetIText(tempHandle, myStr);
  536.         
  537.         /* make sure there are 4 characters here, please */
  538.         if (myStr[0] == 4) {
  539.             BlockMove((Ptr)&myStr[1], (Ptr)&theType, sizeof(theType));
  540.             /* reality check to see if there are any of these at this time */
  541.             tempItem = Count1Resources(theType);
  542.             if (tempItem) {
  543.                 /* clear the menu out before I add new things*/
  544.                 tempItem = CountMItems(GetMHandle(kToolsMenu));
  545.                 
  546.                 /* I want to add below the dividing line */
  547.                 tempItem -= kTestMenuDivider;
  548.                 while (tempItem) {
  549.                     DelMenuItem(GetMHandle(kToolsMenu), kTestMenuDivider + 1);
  550.                     
  551.                     tempItem--;
  552.                 }
  553.                 
  554.                 /* call my routine */
  555.                 MyAddResMenu(theType, GetMHandle(kToolsMenu), kTestMenuDivider);
  556.             } else {
  557.                 /* yell because there are none of that type around */
  558.                 ParamText(myStr, "", "", "");
  559.                 CautionAlert(kNoneOfThatType, nil);
  560.             }
  561.         }
  562.     }
  563.     DisposDialog(myDialog);
  564.     
  565. }
  566.  
  567. /* MyAddResMenu does, basically, what AddResmenu does, it does an */
  568. /* "insert sort" (one of the Comp. Sci. types around here told me to call it that) */
  569. /* of the names of the resources.It uses IUCompString for */
  570. /* International Reasons (KFJC 89.7, 12-3 Sundays) */
  571. /* The only thing it really does differently is includes items that don't have */
  572. /* names by including the 'unnamedX' string. */
  573. /* Also notice that, since I'm using InsMenuItem I have to parse the*/
  574. /* name string and take out any menu manager meta-characters before I insert things */
  575. /* so I don't get strange command keys from a name like "Alert/Warning 1" */
  576.  
  577. void MyAddResMenu(ResType theType, MenuHandle theMenu, short afterItem)
  578. {
  579.     short originalCount = afterItem;
  580.     short resourceCount = Count1Resources(theType);
  581.     short index = 1;
  582.     short unnamedCount = 0;
  583.     short qq;
  584.     ResType theIndexType;
  585.     short theID;
  586.     Str255 theName;
  587.     Str32 unusedWord;
  588.     Str255 tempString;
  589.     Handle tempHandle;
  590.     Boolean oldResLoad = *((Boolean *)0xA5E);
  591.     Boolean addedIt = false;
  592.     
  593.     GetIndString(unusedWord, kGenStrings, kUnnamedString);
  594.     SetResLoad(false);                                      /* don't want to load the resources */
  595.     do {
  596.         tempHandle = Get1IndResource(theType, index);
  597.         theName[0] = 0;
  598.         GetResInfo(tempHandle, &theID, &theIndexType, &theName);
  599.         /* Check the name, if no name tell it so... */
  600.         if (theName[0] == 0) {
  601.             BlockMove((Ptr)&unusedWord, (Ptr)&theName, unusedWord[0] + 1);
  602.             NumToString((long)unnamedCount, tempString);
  603.             if ((theName[0] + tempString[0]) < 254) {
  604.                 BlockMove((Ptr)&tempString[1], (Ptr)(&theName[1] + theName[0]), tempString[0]);
  605.                 theName[0] += tempString[0];
  606.             }
  607.             unnamedCount++;
  608.         }
  609.         CleanUpMetaChars(theName);
  610.         /* here's where you sort in the menu items */
  611.         /* it goes roughly like.... */
  612.         for (qq = afterItem + 1; qq < CountMItems(theMenu) + 1; qq++) {
  613.             GetItem(theMenu, qq, &tempString);
  614.             if (IUCompString(theName, tempString) == -1) {
  615.                 /* new string is less than an existing name */
  616.                 /* so insert it before it */
  617.                 InsMenuItem(theMenu, theName, qq - 1);
  618.                 addedIt = true;
  619.                 break;                                      /* leave the 'for' loop */
  620.             }
  621.         }
  622.         /* If it didn't sort in, just add it to the end of the menu */
  623.         if (!addedIt)
  624.             InsMenuItem(theMenu, theName, CountMItems(theMenu) + 1);
  625.         addedIt = false;
  626.         index++;
  627.     }
  628.             while (index <= resourceCount);
  629.     SetResLoad(oldResLoad);
  630. }
  631.  
  632. /* Some dialog filtering things */
  633. /* TabRetEsc toggles the cancel or OK button for keystrokes, and */
  634. /* treats a Tab press as selecting the whole edit line contents */
  635.  
  636. Boolean TabRetEsc(DialogPtr inputDialog, EventRecord *myDialogEvent, short *theDialogItem)
  637. {
  638.     Boolean returnValue = false;
  639.     long tilticks;
  640.     WindowPtr tempWindowPtr;
  641.     char theKey = myDialogEvent->message &charCodeMask;
  642.     GetPort(&tempWindowPtr);
  643.     SetPort(inputDialog);
  644.     switch (theKey) {
  645.         case kReturnKey:
  646.         case kEnterKey:                                     /* enter key */
  647.             /* This filters for Return or Enter as item 1, and Esc as item 2 */
  648.             *theDialogItem = ok;                            /* change whatever the current item is to the OK item */
  649.             /* now we need to invert the button */
  650.             HiliteControl(SnatchHandle(inputDialog, ok), inButton);
  651.             Delay(8, &tilticks);                            /* wait about 8 ticks so they can see it */
  652.             HiliteControl(SnatchHandle(inputDialog, ok), false);
  653.             returnValue = true;
  654.             break;
  655.             /* This filters the escape key as the same as item 2 (the canx button, usually ) */
  656.         case kEscKey:
  657.             *theDialogItem = cancel;
  658.             HiliteControl(SnatchHandle(inputDialog, cancel), inButton);
  659.             Delay(8, &tilticks);                            /* wait about 8 ticks so they can see it */
  660.             HiliteControl(SnatchHandle(inputDialog, cancel), false);
  661.             returnValue = true;
  662.             break;
  663.         case kTabKey:
  664.             /* I'm filtering the tab key here so a tab selects all the */
  665.             /* text in the edit line, as a convinience */
  666.             SelIText(inputDialog, kResTypeEditLine, 0, 5);
  667.             returnValue = true;                             /* don't allow edit line swaps */
  668.             break;
  669.     }
  670.     SetPort(tempWindowPtr);
  671.     
  672.     return(returnValue);
  673.     
  674. }
  675.  
  676. /* Main dialog filter */
  677. pascal Boolean filterIt(DialogPtr inputDialog, EventRecord *myDialogEvent, short *theDialogItem)
  678. {
  679.     
  680.     Boolean returnVal = false;
  681.     ModalFilterProcPtr theModalProc;
  682.     char theKey;
  683.     Rect tempRect;
  684.     short tempItem;
  685.     Handle tempHandle;
  686.     char tempKey;
  687.     Str255 myStr;
  688.     long offset;
  689.     short selection;
  690.     long scrapLen;
  691.     short resultLen;
  692.     Boolean wasAKey = false;
  693.     if (myDialogEvent->what == updateEvt && myDialogEvent->message != inputDialog) {
  694.         /* May be a pending update event for another window, handle it so */
  695.         /* other layers get time */
  696.         windowCHandle tempWCH;
  697.         WindowPtr theWindow = (WindowPtr)myDialogEvent->message;
  698.         /* draw my window if it's really mine */
  699.         if (((WindowPeek)theWindow)->windowKind == kMyDocumentWindow) {
  700.             tempWCH = (windowCHandle)GetWRefCon(theWindow);
  701.             (ProcPtr)((*tempWCH)->drawMe)((WindowPtr)theWindow);
  702.             
  703.             *theDialogItem = 0;
  704.             returnVal = true;
  705.         }
  706.     } else {
  707.         wasAKey = (myDialogEvent->what == keyDown) || (myDialogEvent->what == autoKey);
  708.         
  709.         if ((wasAKey)) {
  710.             /* first check on the Big Three, tab, return, and escape */
  711.             if (!(returnVal = TabRetEsc(inputDialog, myDialogEvent, theDialogItem))) {
  712.                 
  713.                 /* not one of those, see if this keystroke will fit */
  714.                 /* in the edit line (restricted to 4 characters for a ResType) */
  715.                 
  716.                 /* Here I'm seeing if anything is selected, and getting the length */
  717.                 /* of the desk scrap in case the user presses */
  718.                 /* Copy or Paste keys */
  719.                 
  720.                 selection = HasSelectionRange((DialogPeek)inputDialog);
  721.                 scrapLen = GetScrap(nil, 'TEXT', &offset);
  722.                 
  723.                 GetDItem(inputDialog, kResTypeEditLine, &tempItem, &tempHandle, &tempRect);
  724.                 GetIText(tempHandle, myStr);
  725.                 
  726.                 /* calculate the result of adding the scrap to the current record.We use */
  727.                 /* this in a few places here */
  728.                 resultLen = myStr[0] + (scrapLen - selection);
  729.                 
  730.                 theKey = myDialogEvent->message & charCodeMask;
  731.                 tempKey = theKey;
  732.                 if (tempKey >= 0x61 && tempKey <= 0x7a)
  733.                     tempKey -= 0x20;
  734.                 
  735.                 if (myStr[0] > 3) {                         /* over 4, see what it is */
  736.                     
  737.                     if (IsEditKey(theKey, myDialogEvent->modifiers)) {
  738.                         /* it was an editing key, but it MAY be a command-V. */
  739.                         /* If it's a command-V then we won't allow it UNLESS */
  740.                         /* there is a slection range AND the new data won't overrun things */
  741.                         if ((tempKey == 'V') && (myDialogEvent->modifiers & cmdKey)) {
  742.                             
  743.                             /* this was a paste.check selection range and scrap len*/
  744.                             if (resultLen < 4) {
  745.                                 returnVal = false;          /* net result is4 or less */
  746.                             } else {
  747.                                 SysBeep(1);
  748.                                 returnVal = true;
  749.                             }
  750.                         } else {
  751.                             returnVal = false;              /* don't filter out editing keys */
  752.                         }
  753.                     } else {
  754.                         /* One more check (this can get complicated, huh?) */
  755.                         /* We now look to see if there is a selection range.If there */
  756.                         /* is a range of 1 or more characters, then the one character they are entering */
  757.                         /* now will replace that, and we'll end up with _less_ than 4 (or equal) */
  758.                         /* to do this, we have to get the TERecord out of the dialog.*/
  759.                         /* I'm going to do this in a seperate function */
  760.                         if (selection == nil) {
  761.                             SysBeep(1);                     /* complain a little */
  762.                             returnVal = true;               /* tell the dialog manager that we handled this already and */
  763.                             /* it doesn't have to, so the keystroke will _not_ get */
  764.                             /* added to the edit line */
  765.                         }
  766.                     }
  767.                 } else {
  768.                     /* even if we're less than 4 currently, a Command-V (paste) could put us over */
  769.                     /* so check it out */
  770.                     
  771.                     if ((tempKey == 'V') && (myDialogEvent->modifiers & cmdKey)) {
  772.                         
  773.                         /* Gettting the scrap with a nil handle, which does not give us data, just */
  774.                         /* returns the size */
  775.                         if (resultLen > 3) {
  776.                             SysBeep(1);                     /* complain a little */
  777.                             returnVal = true;               /* tell the dialog manager that we handled this already and */
  778.                             
  779.                         }
  780.                     }
  781.                 }
  782.             }
  783.         }
  784.     }
  785.     if (!returnVal) {
  786.         
  787.         OSErr myErr = GetStdFilterProc(&theModalProc);
  788.         if (myErr == noErr)
  789.             returnVal = theModalProc(inputDialog, myDialogEvent, theDialogItem);
  790.     }
  791.     return(returnVal);
  792. }
  793.  
  794. short HasSelectionRange(DialogPeek inputDialog)
  795. {
  796.     TEHandle theTERecord = inputDialog->textH;
  797.     short returnVal = (*theTERecord)->selEnd -(*theTERecord)->selStart;
  798.     
  799.     return(returnVal);
  800. }
  801.  
  802. /* end HasSelectionRange */
  803.  
  804. /* a little utility to see if the current key is an edit-type key */
  805. Boolean IsEditKey(char theKey, short modifiers)
  806. {
  807.     register qq;
  808.     Boolean returnVal = false;
  809.     char editChars[] =  {
  810.         kLeftArrow, kUpArrow, kRightArrow, kDownArrow, kBackSpace, kEscKey
  811.     };
  812.     char commandEdits[] =  {
  813.         'C', 'V', 'P'
  814.     };
  815.     for (qq = 0; qq < sizeof(editChars) / sizeof(char); qq++) {
  816.         if (theKey == editChars[qq])
  817.             returnVal = true;
  818.     }
  819.     if (returnVal != true && (modifiers & cmdKey)) {
  820.         /* check for XCP */
  821.         /* Do you want me to use 'toupper()'?What! And link in all of StdLib! aggggg */
  822.         if (theKey >= 0x61 && theKey <= 0x7a)
  823.             theKey -= 0x20;
  824.         for (qq = 0; qq < sizeof(commandEdits) / sizeof(char); qq++) {
  825.             if (theKey == commandEdits[qq])
  826.                 returnVal = true;
  827.         }
  828.     }
  829.     return(returnVal);
  830. }
  831.  
  832. /* end IsEditKey */
  833.  
  834. /* Gets the ControlHandle for the item you want in the dialog box thebox.*/
  835. /* Handy for setting checkboxes and radio buttons */
  836. /* This is the _most_ copied routine from this file */
  837. ControlHandle SnatchHandle(DialogPtr thebox, short theGetItem)
  838. {
  839.     short itemtype;
  840.     Rect itemrect;
  841.     Handle thandle;
  842.     
  843.     GetDItem(thebox, theGetItem, &itemtype, &thandle, &itemrect);
  844.     return((ControlHandle)thandle);
  845. }
  846.  
  847. /* end SnatchHandle */
  848.  
  849. void CleanUpMetaChars(Str255 theString)
  850. {
  851.     char metaKeys[] =  {
  852.         ';', '^', '!', '<', '/', '('
  853.     };
  854.     register qq, ii;
  855.     
  856.     qq = theString[0];
  857.     while (qq) {
  858.         for (ii = 0; ii < sizeof(metaKeys) / sizeof(char); ii++) {
  859.             if (theString[qq] == metaKeys[ii])
  860.                 theString[qq] = '•';                         /* replace with a Spot */
  861.         }
  862.         qq--;
  863.     }
  864. }
  865.  
  866.  
  867. #pragma segment Initialize
  868. void InitalizeApp(void)
  869. {
  870.     Handle myMenu;
  871.     MenuHandle helpHandle, appleMenuHandle;
  872.     StringHandle helpString;
  873.     short count;
  874.     long vers;
  875.     MaxApplZone();
  876.     InitGraf((Ptr)&qd.thePort);
  877.     InitFonts();
  878.     InitWindows();
  879.     InitMenus();
  880.     TEInit();
  881.     InitDialogs(nil);
  882.     InitCursor();
  883.     /* Check system version */
  884.     Gestalt(gestaltSystemVersion, &vers);
  885.     vers = (vers >> 8) & 0xf;                               /* shift result over and mask out major version number */
  886.     if (vers < 7) {
  887.         StopAlert(kBadSystem, nil);
  888.         ExitToShell();
  889.     }
  890.     InitAEStuff();
  891.     /* set up my menu junk */
  892.     myMenu = GetNewMBar(kMBarID);
  893.     SetMenuBar(myMenu);
  894.     appleMenuHandle = GetMHandle(kAppleMenu);
  895.     AddResMenu(appleMenuHandle, 'DRVR');
  896.     
  897.     /* now install my Help menu item in the Help Manager's menu */
  898.     HMGetHelpMenuHandle(&helpHandle);                       /* Get the Hlpe menu handle */
  899.     count = CountMItems(helpHandle);                        /* How many items are there? */
  900.     helpString = GetString(kHelpString);                    /* get my help string */
  901.     DetachResource(helpString);                             /* detach it */
  902.     HNoPurge(helpString);
  903.     MoveHHi((Handle)helpString);
  904.     HLock((Handle)helpString);
  905.     InsMenuItem(helpHandle, (Ptr)*helpString, count + 1);       /* insert my item in the Help menu */
  906.     gHelpItem = CountMItems(helpHandle);                    /* The number of the item */
  907.     
  908.     DrawMenuBar();
  909.     GetCurrentProcess(&gOurSN);                             /* Get our process serial number for later use, if needed */
  910.     
  911. }
  912.  
  913.  
  914. #pragma segment Main
  915.